var dataUrl = null;
$(function () {
    // 绑定取消按钮事件
    $(".cancel").click(function () {
        window.location.reload();
    });
    init();
    $("form").validate({
        submitHandler: function (form) {// 必须写在验证前面，否则无法ajax提交
            //jquery获取复选框值
            if (!checkForm()) {
                return;
            }
            var num = 0;
            var postPropPersonIds = "";
            $(".post-person").each(function () {
                var postId = $(this).attr("dataId");
                var ids = getpostPersonIds(postId);
                if (ids == "") {
                    num = postId;
                    return ;
                    // continue;
                }
                postPropPersonIds += (postId + "-" + ids + "&");
                // postPropIds+= $(this).val();
            });
            if(postPropPersonIds==""){
                layer.msg("请选择调配人员");
                return;
            }
            /*if (num != 0) {
                var dataName = $("#inspectPerson" + num).attr("dataName");
                layer.msg("请选择" + dataName);
                return;
            }*/
            $("#postPropPersonIds").val(postPropPersonIds);
            // var chk_value =[];//定义一个数组
            var index = layer.load(1, {shade: false});
            $("#submitButton").attr("disabled", "disabled");
            $(form).ajaxSubmit({
                dataType: "text",
                success: function (data) {
                    $("#submitButton").removeAttr("disabled");
                    layer.close(index);
                    if (data == "success") {
                        // layer.confirm('添加成功!是否关闭窗口?', function (index) {
                        layer.msg("添加成功！");
                        // window.location.reload();
                        return false;
                        // });
                    } else {
                        layer.alert('添加失败！', 3);
                    }
                }
            });
        },
        errorPlacement: function (error, element) {// 自定义提示错误位置
            $(".l_err").css('display', 'block');
            // element.css('border','3px solid #FFCCCC');
            $(".l_err").html(error.html());
        },
        success: function (label) {// 验证通过后
            $(".l_err").css('display', 'none');
        }
    });
});
function init() {
    // dataUrl = $("#dataUrl").val();
    dataUrl ="/modules";
    getProjectNameList();
    $("#postPerson").html("");
}
function checkForm() {
    if ($("#projectId").val() == '') {
        layer.msg('请选择工程名称');
        return false;
    }
    if ($("#corpId").val() == '') {
        layer.msg('请选择单位名称');
        return false;
    }
    return true;
}
/**
 * 项目工程下拉列表
 */
function getProjectNameList() {
    var url = dataUrl + "/projectManage/getProjectByPerson?personCorpId="+$("#personCorpId").val()+"&newDate="+(new Date().getTime());
    $.ajax({
        url: url,
        method: "get",
        dataType: "json",
        async: true,
        cache: false,
        crossDomain: true == !(document.all),
        success: function (result) {
            var html = "";
            html += "<option value=''>------请选择------</option>";
            if (result != null) {
                for (var i = 0; i < result.length; i++) {
                    html += "<option value='" + result[i].id + "'>" + (result[i].caption) + "</option>";
                }
                $("#projectId").html(html);
            } else {
                layer.msg("获取列表信息错误，请联系管理员！");
            }
        }
    });
}
/**
 * 单位列表
 * @param projectId
 */
function getCropList(projectId) {
    var url = dataUrl + "/projectManage/findCorpByProjectId?projectId=" + projectId+"&personCorpId="+$("#personCorpId").val()+"&newDate="+(new Date().getTime());;
    $.ajax({
        url: url,
        method: "get",
        dataType: "json",
        async: true,
        cache: false,
        crossDomain: true == !(document.all),
        success: function (result) {
            var html = "";
            html += "<option value=''>------请选择------</option>";
            if (result != null) {
                for (var i = 0; i < result.length; i++) {
                    html += "<option corpPropId='" + result[i].corpPropId + "'corpId='" + result[i].corpId + "'corpPropCaption='"
                        + result[i].corpPropCaption + "' value='" + result[i].corpId + "'>" + (result[i].corpName) + "</option>";
                }
                $("#corpId").html(html);
            } else {
                layer.msg("获取列表信息错误，请联系管理员！");
            }
        }
    });
}
function getCropPersonDetails() {
    var options = $("#corpId option:selected");
    $("#cropPropName").text(options.attr("corpPropCaption")!=null?options.attr("corpPropCaption"):"");
    $("#cropName").text("(" + options.text() + ")");
    getCropPostAndCropPerson(options.attr("corpId"), options.attr("corpPropId"));
}
/**
 * 获取单位性质
 * @param cropId
 */
function getpostPersonIds(postId) {
    var postPersonId = "";
    $('#inspectPerson' + postId + ' input[name="checkPerson"]:checked').each(function () {//遍历每一个名字为interest的复选框，其中选中的执行函数
        postPersonId += $(this).val() + ",";//拼接
        // chk_value.push($(this).val());//将选中的值添加到数组chk_value中

    });
    return postPersonId;
}
/**
 * 获取单位性质岗位人员
 * @param cropId
 */
function getCropPostAndCropPerson(corpId, corpPropId) {

    var personArray = new Array();

    var url = dataUrl + "/projectManage/persons?corpId=" + corpId+"&newDate="+(new Date().getTime());
    $.ajax({
        url: url,
        method: "get",
        dataType: "json",
        async: false,
        cache: false,
        crossDomain: true == !(document.all),
        success: function (result) {
            if (result != null) {
                personArray = result;
            } else {
                layer.msg("获取列表信息错误，请联系管理员！");
            }
        }
    });
    var corpPostUrl = dataUrl + "/projectManage/findCorpPostByPropId?corpPropId=" + corpPropId+"&newDate="+(new Date().getTime());;
    $.ajax({
        url: corpPostUrl,
        method: "get",
        dataType: "json",
        async: true,
        cache: false,
        crossDomain: true == !(document.all),
        success: function (result) {
            var html = "";
            // html += "<option value=''>------请选择------</option>";
            if (result != null) {

                for (var i = 0; i < result.length; i++) {
                    var existencePersonArray = getPersonProjectList(result[i].id);
                    var select = getExistencePersonCheckbox(existencePersonArray,personArray);
                    html += '   <div class="form-group-div form-layer-input clearfix">' +
                        '<label class="control-label3">' + (result[i].caption) + '：</label>' +
                        '<div class="input-medium3 form-control m-b" >' +

                        '<span style="width: 200px;display: inline-block;background-color: white;min-height: 32px" ' +
                        'id="inspectPersonSpan' + result[i].id + '">';
                    if (existencePersonArray != null&&existencePersonArray.length>0) {
                        html += getExistencePersonName(existencePersonArray,personArray);
                    }
                    html += '</span><a href="javascript:checkedInspectPerson(\'' +
                        result[i].caption + '\',' + result[i].id + ')">选择' + result[i].caption + '</a>' +
                        '</div>' +
                        '<div id="inspectPerson' + result[i].id + '" dataName="' + result[i].caption + '" style="display: none;" dataId="' +
                        result[i].id + '" class="post-person">';

                    html += select;

                    html += '</div>' +
                        '</div>'
                    // html += "<option value='" + result[i].id + "'>" + (result[i].caption) + "</option>";
                }
                $("#postPerson").html(html);
            } else {
                layer.msg("获取列表信息错误，请联系管理员！");
            }
        }
    });
}
function checkedInspectPerson(title, postId) {
    pageii = layer.open({
        title: [title],
        type: 1,
        fixed: true,
        //shadeClose : true,
        area: ["400px", ""],
        btn: ['确定'],
        content: $("#inspectPerson" + postId),
        yes: function (index, layero) {
            var inspectPersonSpan = "";
            // inspectPersonSpan = $('input[name="checkPerson' + postId + '"]:checked').next().text();
            $('#inspectPerson' + postId + ' input[name="checkPerson"]:checked').each(function () {//遍历每一个名字为interest的复选框，其中选中的执行函数
                var id = $(this).val();

                inspectPersonSpan += $("#span" + id).text() + ",";//拼接
                // chk_value.push($(this).val());//将选中的值添加到数组chk_value中

            });
            $("#inspectPersonSpan" + postId).text(inspectPersonSpan);
            layer.close(index);
        }
    });
}
function getPersonProjectList(postId) {
    var existencePersonArray = new Array();
    var projectId = $("#projectId").val();
    var url = dataUrl + "/projectManage/getProjectPerson?postId=" + postId + "&projectId=" + projectId+"&newDate="+(new Date().getTime());
    $.ajax({
        url: url,
        method: "get",
        dataType: "json",
        async: false,
        cache: false,
        crossDomain: true == !(document.all),
        success: function (result) {
            if (result != null) {
                existencePersonArray=result;
            }
        }
    });
    return existencePersonArray;
}
function getExistencePersonName(list, personList) {
    var names = "";
    for (var i = 0; i < personList.length; i++) {
        for (var j = 0; j < list.length; j++) {
            if (personList[i].id==list[j].personId) {
                names+=personList[i].name+",";
            }
        }
    }
  return names;
}
function getExistencePersonCheckbox(list, personList) {
    var select = "";
    for (var i = 0; i < personList.length; i++) {
        select += "<b style='width: 100px'><input name='checkPerson' type='checkbox' value='" + personList[i].id +"' ";
        for (var j = 0; j < list.length; j++) {
            if (personList[i].id==list[j].personId) {
                select +=    " checked='checked' ";
            }
        }
        select +=   "/><span id='span" + personList[i].id + "' style='display: inline-block;width: 80px'>" + (personList[i].name) + "</span></b>";
    }

  return select;
}